package com.mohan.yygh.cmn.service.impl;

import com.alibaba.excel.EasyExcel;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mohan.model.cmn.Dict;
import com.mohan.vo.cmn.DictEeVo;
import com.mohan.yygh.cmn.listener.DictListener;
import com.mohan.yygh.cmn.mapper.DictMapper;
import com.mohan.yygh.cmn.service.DictService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class DictServiceImpl extends ServiceImpl<DictMapper, Dict> implements DictService {
  @Override
  @Cacheable(value = "dict",keyGenerator = "keyGenerator")
  public List<Dict> findChildData(Long id) {
    return baseMapper
            .selectList(new QueryWrapper<Dict>().eq("parent_id", id))
            .stream()
            .map(item -> {
              item.setHasChildren(isChildren(item.getId()));
              return item;
            }).collect(Collectors.toList());
  }

  @Override
  public void exportDict(HttpServletResponse response) {
    try {
      // 设置下载的信息
      response.setContentType("application/vnd.ms-excel");
      response.setCharacterEncoding("utf-8");
      // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
      String fileName = URLEncoder.encode("数据字典", "UTF-8");
      response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
      // 查询数据库
      List<DictEeVo> collect = baseMapper
              .selectList(null).stream()
              .map(item -> {
                DictEeVo dictEeVo = new DictEeVo();
                BeanUtils.copyProperties(item, dictEeVo);
                return dictEeVo;
              }).collect(Collectors.toList());

      EasyExcel.write(response.getOutputStream(),DictEeVo.class).sheet("dict")
              .doWrite(collect);
    } catch (IOException e) {
      e.printStackTrace();
    } finally {
    }
  }

  @Override
  @CacheEvict(value = "dict",allEntries = true)
  public void importData(MultipartFile file) {
    try {
      EasyExcel.read(file.getInputStream(),DictEeVo.class,new DictListener(this)).sheet().doRead();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

  //判断下面是否有子节点
  private boolean isChildren(Long id) {
    return baseMapper.selectCount(new QueryWrapper<Dict>().eq("parent_id", id)) > 0;
  }
}
